"""
批量裁剪图片为256*256块
"""
from PIL import Image
import os
from tqdm import tqdm

def crop_images_to_256_blocks(folder_path, output_folder):
    # 确保输出文件夹存在
    if not os.path.exists(output_folder[0]):
        os.makedirs(output_folder[0])

    # 获取所有图片文件列表
    img_files = [f for f in sorted(os.listdir(folder_path[0]))
                 if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif'))]

    # 使用tqdm包装外层循环（固定宽度和刷新频率）
    for filename in tqdm(img_files,
                        desc="处理图片",
                        ncols=80,               # 固定进度条宽度
                        dynamic_ncols=False,     # 禁止动态调整宽度
                        mininterval=0.1):       # 设置最小刷新间隔
        file_path = os.path.join(folder_path[0], filename)
        with Image.open(file_path) as img:
            width, height = img.size
            base_name = os.path.splitext(filename)[0]
            counter = 1

            # 使用tqdm包装宽度方向的裁剪循环
            for i in range(0, width, 256):       # 降低内层刷新频率
                for j in range(0, height, 256):
                    cropped_img = img.crop((i, j, i + 256, j + 256))
                    output_filename = f"{base_name}_{counter}{os.path.splitext(filename)[1]}"
                    output_path = os.path.join(output_folder[0], output_filename)
                    cropped_img.save(output_path)
                    counter += 1

# 大图路径和输出路径
folder_path = [['../XJU1_jsonToMask/train_img_big'], ['../XJU1_jsonToMask/train_lab_big']]
output_folder = [['train_img_small'], ['train_lab_small']]

# 使用tqdm包装主循环
for i in range(len(folder_path)):
    if not os.path.exists(output_folder[i][0]):
        os.makedirs(output_folder[i][0])
    print(f"正在处理 {folder_path[i][0]} 中的图片...")
    crop_images_to_256_blocks(folder_path[i], output_folder[i])